package keter.web.filter;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import keter.framework.web.util.RequestUtil;
import keter.framework.web.util.ResponseUtil;
import keter.model.Role;

@WebFilter(filterName="permissionFilter",urlPatterns={"/app/*"})
public class PermissionFilter implements Filter {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(PermissionFilter.class);

//    private String  excludes = "index,static,public,captcha,loginsuccess";

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
    	HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String[] permissionsArr = getPermissions().split(",");
        logger.info("~~~~~ \n uri:{},\n Permissions:{} \n~~~~~~~~~~",
        		request.getRequestURI(),
        		permissionsArr);
        if(!StringUtils.containsAny(request.getRequestURI(),permissionsArr)){
        	if(RequestUtil.isAjax(request)){
        		ResponseUtil.print("access:denied", response);
        	}
        	else{
        		ResponseUtil.printHtml("阻止访问！", response);
        	}
        }
        else{
            logger.info("允许访问");
            chain.doFilter(request, response);
        }
    }
 
    /**
     * <p>Method ：getPermissions
     * <p>Description : 从spring容器中获取当前用户的角色权限信息
     *
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    private String getPermissions(){
    	@SuppressWarnings("unchecked")
		Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    	String permissions = "";
    	for (Iterator iterator = authorities.iterator(); iterator.hasNext();) {
			GrantedAuthority grantedAuthority = (GrantedAuthority) iterator.next();
			String roleName = grantedAuthority.getAuthority();
			if(roleName.equals("ROLE_ANONYMOUS")){
				return "ROLE_ANONYMOUS";
			}
			permissions += Role.dao.findPermissionByName(roleName) +",";
		}
    	return permissions;
    }
    
    @Override
    public void destroy() {
    }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

}
